package com.example.demo.controller;

import com.example.demo.code.CustomStatusCode;
import com.example.demo.dto.LoginRequest;
import com.example.demo.error.ApiResponse;
import com.example.demo.service.JwtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final AuthenticationManager authenticationManager;
    private final JwtService jwtService;

    public AuthController(AuthenticationManager authenticationManager, JwtService jwtService) {
        this.authenticationManager = authenticationManager;
        this.jwtService = jwtService;
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse> authenticateUser(@RequestBody LoginRequest loginRequest) {
        try {
            logger.info("Authenticating user: {}", loginRequest.getUsername());
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );

            if (authentication.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authentication);
                String jwt = jwtService.generateJwtToken(authentication);
                return ResponseEntity.ok(new ApiResponse(CustomStatusCode.LOGIN_SUCCESS, jwt, 1));
            } else {
                logger.warn("Authentication failed for user: {}", loginRequest.getUsername());
                return ResponseEntity.ok(new ApiResponse(CustomStatusCode.UNAUTHORIZED, null, 0));
            }
        } catch (AuthenticationException e) {
            logger.error("Authentication error for user: {}", loginRequest.getUsername(), e);
            return ResponseEntity.ok(new ApiResponse(CustomStatusCode.UNAUTHORIZED, null, 0));
        }
    }
}